#import "LibAppleAuthStoragePlugin.h"
#import "AppleAuthenticator.h"
#import "AppleICloudStorage.h"


@interface LibAppleAuthStoragePlugin()<AppleAuthenticatorDelegate>

@property (nonatomic, strong) AppleAuthenticator *appleAuthenticator;
@property (nonatomic, strong) AppleICloudStorage *appleICloudStorage;


@property (nonatomic, copy) FlutterResult result;

@end


@implementation LibAppleAuthStoragePlugin


+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"lib_apple_auth_storage"
                                     binaryMessenger:[registrar messenger]];
    LibAppleAuthStoragePlugin* instance = [[LibAppleAuthStoragePlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (AppleAuthenticator *)appleAuthenticator {
    if (!_appleAuthenticator) {
        _appleAuthenticator = [[AppleAuthenticator alloc] init];
        _appleAuthenticator.delegate = self;
    }
    return _appleAuthenticator;
}

- (AppleICloudStorage *)appleICloudStorage {
    if (!_appleICloudStorage) {
        _appleICloudStorage = [[AppleICloudStorage alloc] init];
    }
    return _appleICloudStorage;
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    self.result = result;
    
    @try {
        if ([call.method isEqualToString:@"login"]) {
            UIWindow *window = [self getShowWindow];
            if (!window) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setValue:@"-1" forKey:@"code"];
                [dict setValue:@"Failed to get windowv" forKey:@"error"];
                result([LibAppleAuthStoragePlugin convertObjectToJson:dict]);
                return;
            }
            [self.appleAuthenticator signInWithWithWindow:window];
            return;
        }
        
         NSDictionary *arguments = [LibAppleAuthStoragePlugin convertJsonToObject:call.arguments];
        
         if (!arguments) {
             result([FlutterError errorWithCode:@"-1" message:@"Parameter error" details:nil]);
             return;
         }
        
        if ([call.method isEqualToString:@"storage"]) {
            
            NSString *fileName = arguments[@"fileName"];
            NSString *content = arguments[@"content"];
            NSLog(@"上传文件内容:%@", fileName);
            NSLog(@"上传文件内容content:%@", content);
            if (fileName && content) {

                [self.appleICloudStorage writeWithData:[content dataUsingEncoding:NSUTF8StringEncoding] fileName:fileName completion:^(NSError * _Nullable error) {
                    
                       
                    if (error) {
                        
                        NSLog(@"上传文件error:%@", error.description);
                        result([FlutterError errorWithCode:@"AppleAuthStoragePlugin" message:error.localizedFailureReason details:nil]);
                        return;
                    }
                    
                    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                    [dict setValue:@"0" forKey:@"code"];
                    NSLog(@"上传文件结果dict:%@", dict);
                    result([LibAppleAuthStoragePlugin convertObjectToJson:dict]);
                }];
            } else {
                result([FlutterError errorWithCode:@"AppleAuthStoragePlugin" message:@"Invalid arguments" details:nil]);
            }
            return;
        }
        
        
        if ([call.method isEqualToString:@"getStorageContent"]) {
            
            NSString *fileName = arguments[@"fileName"];
            [self.appleICloudStorage readWithFileName:fileName completion:^(NSData * _Nullable fileData, NSError * _Nullable error) {
                            
                NSLog(@"获取到文件名:%@", fileName);
                if (error) {
                    result([FlutterError errorWithCode:@"AppleAuthStoragePlugin" message:error.localizedFailureReason details:nil]);
                    return;
                }
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setValue:@"0" forKey:@"code"];
                [dict setValue:[[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding] forKey:@"fileContent"];
                 NSLog(@"获取到文件内容:%@", dict[@'fileContent']);
                result([LibAppleAuthStoragePlugin convertObjectToJson:dict]);
            }];
            return;
        }
        
        if ([call.method isEqualToString:@"getPlatformVersion"]) {
            result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
        }
        
        result(FlutterMethodNotImplemented);
        
    } @catch (NSException *exception) {
        result([FlutterError errorWithCode:@"-1" message:@"Removal occurs" details:nil]);
    } @finally {
        
    }
    
}

- (void)appleAuthenticator:(AppleAuthenticator *)manager didCompleteWithError:(NSError *)error {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:@"-1" forKey:@"code"];
    [dict setValue:error.localizedFailureReason forKey:@"error"];
    self.result([LibAppleAuthStoragePlugin convertObjectToJson:dict]);
}

- (void)appleAuthenticator:(AppleAuthenticator *)manager didCompleteWithResult:(HJAppleSignInResult *)result {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:@"0" forKey:@"code"];
    [dict setValue:result.user.userID forKey:@"userID"];
    [dict setValue:result.user.email forKey:@"email"];
    [dict setValue:result.user.fullName forKey:@"fullName"];
    [dict setValue:result.user.identityToken forKey:@"identityToken"];
    self.result([LibAppleAuthStoragePlugin convertObjectToJson:dict]);
}

- (void)appleAuthenticator:(AppleAuthenticator *)manager appleIdStateChanged:(NSDictionary *)info {
    NSLog(@"appleIdStateChanged = %@", info);
}


+ (nullable NSString *)convertObjectToJson:(id)object {
    if ([object isKindOfClass:NSString.class]) {
        return object;
    }
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
    if (!jsonData) {
        return nil;
    }
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}


+ (id)convertJsonToObject:(NSString *)jsonString {
    if (![jsonString isKindOfClass:NSString.class]) {
        return jsonString;
    }
    
    NSError *error;
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    if (!jsonData) {
        return nil;
    }
    
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    return jsonObject;
}

- (UIWindow *)getShowWindow {
    UIWindow *mainWindow = [UIApplication sharedApplication].keyWindow;
    if (!mainWindow) {
        mainWindow = [[UIApplication sharedApplication].windows firstObject];
    }
    if (!mainWindow) {
        mainWindow = [[UIApplication sharedApplication].windows firstObject].rootViewController.view.window;
    }
    return mainWindow;
}

@end
